"""settings"""
from contextlib import contextmanager

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from common.environment import DataBaseEnv

# 创建数据库引擎
engine = create_engine(
    f"postgresql://{DataBaseEnv.DB_USER}:{DataBaseEnv.DB_PASSWORD}"
    f"@{DataBaseEnv.DB_HOST}:{DataBaseEnv.DB_PORT}/{DataBaseEnv.DB_NAME}",
    pool_size=10,
    max_overflow=20
)

SessionLocal = scoped_session(
    sessionmaker(autocommit=False, autoflush=False, bind=engine)
)


@contextmanager
def get_db():
    db = SessionLocal()
    try:
        yield db
        db.commit()  # 无异常时提交事务
    except Exception:
        db.rollback()  # 异常时回滚事务
        raise
    finally:
        db.close()  # 始终关闭会话